package org.gateway.server.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * 认证全局过滤器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthorizationFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    	ServerHttpRequest request = exchange.getRequest();
        String token = request.getQueryParams().getFirst("token");
        if (ObjectUtils.isEmpty(token)) {
            log.error("The gateway failed to request authentication, The token parameter is missing!");
            throw new RuntimeException("Unlawful requests, The token parameter is missing!");
        }
        return chain.filter(exchange);
    }

    /**
     * 过滤器 order 值小的过滤器优先执行
     * 同等过滤器order 值相同则按 a-z 自然顺序执行
     * 全局过滤器和局部过滤器 order 值相同时，全局过滤器优先执行
     * 局部过滤器默认执行顺序根据配置中的顺序自动生成，从上往下生成顺序为 1, 2, 3……，也可以实现 Ordered 接口实现自定义顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }

}